/**
 * @file name PListActivity.java
 */
package com.digital.community;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.digital.community.common.utils.HttpUtils;
import com.digital.community.common.utils.StringUtils;
import com.digital.community.common.utils.ToastUtils;

/**
 * 
 * @author yarine.gao
 * @date 2012-11-3
 * @version 1.0.0
 */
public class PListActivity extends Activity {

	private ListView listView;
	
	HashMap<String, String> params = null;
	
	private int currPage = 1;
	private int totalRows = 0;
	private int position = 0;
	
	private TextView nameTxt;
	private TextView genderTxt;
	private TextView nationTxt;
	private TextView updateTxt;
    private TextView delTxt;
    
	private ArrayList<String> nationList;
	private ArrayList<String> cardtypeList;
	private ArrayList<String> genderList;
	@Override
    public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        setContentView(R.layout.tbperson_plist);
        
        Intent intent = getIntent();
        String name = intent.getStringExtra("name");
        String mobile = intent.getStringExtra("mobile");
        String work = intent.getStringExtra("work");
        String cardno = intent.getStringExtra("cardno");
        
        nationList = intent.getStringArrayListExtra("nation");
        cardtypeList = intent.getStringArrayListExtra("cardtype");
        genderList = intent.getStringArrayListExtra("gender");
	
        params = new HashMap<String, String>();
        params.put("name", name);
        params.put("mobile", mobile);
        params.put("work", work);
        params.put("cardno", cardno);
        
        nameTxt = (TextView)findViewById(R.id.txt_name);
        genderTxt = (TextView)findViewById(R.id.txt_gender);
        nationTxt = (TextView)findViewById(R.id.txt_nation);
        updateTxt = (TextView)findViewById(R.id.txt_update);
        delTxt = (TextView)findViewById(R.id.txt_del);
        
        listView = (ListView)findViewById(R.id.list);
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				if (view.getAdapter() != null && view.getCount() > 0) {
					
//					System.out.println("---->firstVisibleItem: " + firstVisibleItem + "  visibleItemCount: " + visibleItemCount
//							+ "  totalItemCount :" + totalItemCount + "  totalRows: " + totalRows);
					if (firstVisibleItem + visibleItemCount == totalItemCount
							&& totalItemCount < totalRows && !isLoading) {
						currPage++;
						position = totalItemCount;
						
						toQueryData();
					}
//					pageView.setText(firstVisibleItem + visibleItemCount + "/"
//							+ totalRows);
				} else {
//					pageView.setText("0/0");
				}
			}
		});
	}
	
    @Override
    protected void onStart() {
    	super.onStart();

    	 isLoading = false;
         currPage = 1;
     	totalRows = 0;
     	position = 0;
     	 list = new ArrayList<Bundle>();
     	toQueryData();
    }
	
	private boolean isLoading = false;
	private ArrayList<Bundle> list = null;
	ProgressDialog proDialog;
	private void toQueryData() {
		if(isLoading) {
			return;
		}
		isLoading = true;
		proDialog = ProgressDialog.show(PListActivity.this, "请等待", "正在请求数据...",true,true);
		new Thread() {
			public void run() {
				
				Bundle bundle = HttpUtils.getPost("toQuery.do", params, 3000, PListActivity.this);
				if(bundle.getInt("code") == HttpUtils.SUCCESS) {
    	    		String content = bundle.getString("content");
    	    		if(StringUtils.isBlank(content) || "[]".equals(content)) {
    	    			handler.sendEmptyMessage(HANDLER_CONN_ERROR);
    	    			return;
    	    		} else {
    	    			try {
    	    				JSONArray json = new JSONArray(content);
    	    				
    	    				totalRows = json.getInt(0);
    	    				for(int i = 1; i < json.length(); i ++) {
    	    					JSONObject obj = json.getJSONObject(i);
    	    					Bundle temp = new Bundle();
    	    					temp.putString("name", obj.getString("name"));
    	    					temp.putString("gender", obj.getString("gender"));
    	    					temp.putString("nation", obj.getString("nation"));
    	    					temp.putString("cardno", obj.getString("cardno"));
    	    					temp.putString("guid", obj.getString("guid"));
    	    					
    	    					list.add(temp);
    	    				}
    	    				
    	    				handler.sendEmptyMessage(HANDLER_CQUERY_CONN_SUCCESS);
    	    			} catch (Exception e) {
    	    				System.out.println(e);
    	    				handler.sendEmptyMessage(HANDLER_CONN_ERROR);
						}
    	    		}
    	    	} else {
    	    		handler.sendEmptyMessage(HANDLER_CONN_ERROR);
    	    	}
			};
		}.start();
	}
	
	private int nameWidth = 0;
	private int genderWidth = 0;
	private int nationWidth = 0;
	private int updateWidth = 0;
	private int delWidth = 0;
	private static final int HANDLER_CONN_ERROR = 100;
    private static final int HANDLER_CQUERY_CONN_SUCCESS = 104;
    private static final int HANDLER_DEL_CONN_ERROR = 105;
    private static final int HANDLER_DEL_ERROR = 106;
    private static final int HANDLER_DEL_SUCCESS = 107;
	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if(proDialog != null && proDialog.isShowing()) {
				proDialog.dismiss();
			}
			isLoading = false;
			switch (msg.what) {
			case HANDLER_CONN_ERROR:
				showDialog(DIALOG_NETWORK_ERROR);
				break;
			case HANDLER_CQUERY_CONN_SUCCESS:
				nameWidth = nameTxt.getWidth();
				genderWidth = genderTxt.getWidth();
				nationWidth = nationTxt.getWidth();
				updateWidth = updateTxt.getWidth();
				delWidth = delTxt.getWidth();
				
				if (list != null && list.size() > 0) {
					listView.setAdapter(new PersonQueryAdapter(list, PListActivity.this));
					if (position > 0) {
						listView.setSelection(position);
					}
				} else {
					listView.setAdapter(null);
				}
				break;
			case HANDLER_DEL_CONN_ERROR:
				showDialog(DIALOG_DEL_CONN_ERROR);
				break;
			case HANDLER_DEL_ERROR:
				showDialog(DIALOG_DEL_ERROR);
				break;
			case HANDLER_DEL_SUCCESS:
				ToastUtils.showTrueToast(PListActivity.this, getLayoutInflater(), "注销成功!", false);
				
				isLoading = false;
				currPage = 1;
				totalRows = 0;
				position = 0;
				list = new ArrayList<Bundle>();
				toQueryData();
				break;
			default:
				break;
			}
			
		};
	};
	
    private static final int DIALOG_NETWORK_ERROR = 200;
    private static final int DIALOG_ADD_ERROR = 201;
    private static final int DIALOG_QUERY_NETWORK_ERROR = 202;
    private static final int DIALOG_DEL_CONN_ERROR = 203;
    private static final int DIALOG_DEL_ERROR = 204;
    @Override
	protected Dialog onCreateDialog(int id) {
		if(!isActive) return null;
		switch (id) {
		case DIALOG_NETWORK_ERROR:
			return new AlertDialog.Builder(this).setTitle("提示信息").setMessage("对不起,网络联接失败!")
						.setPositiveButton("重试", new Retry())
						.setNegativeButton("取消", new Cancle()).create();
//		case DIALOG_ADD_ERROR:
//			return new AlertDialog.Builder(this).setTitle("提示信息").setMessage("对不起,添加失败!")
//						.setPositiveButton("重试", new Retry())
//						.setNegativeButton("取消", new Cancle()).create();
//		case DIALOG_QUERY_NETWORK_ERROR:
//			return new AlertDialog.Builder(this).setTitle("提示信息").setMessage("对不起,网络联接失败!")
//						.setPositiveButton("重试", new RetryQuery())
//						.setNegativeButton("取消", new Cancle()).create();
			
		case DIALOG_DEL_CONN_ERROR:
			return new AlertDialog.Builder(this).setTitle("提示信息").setMessage("对不起,网络联接失败!")
			.setPositiveButton("重试", new RetryDel())
			.setNegativeButton("取消", new Cancle()).create();
		case DIALOG_DEL_ERROR:
			return new AlertDialog.Builder(this).setTitle("提示信息").setMessage("对不起,注销失败!")
						.setPositiveButton("重试", new RetryDel())
						.setNegativeButton("取消", new Cancle()).create();
		default:
			return null;
		}
	}
    
    private class RetryDel implements OnClickListener {
    	@Override
    	public void onClick(DialogInterface dialog, int which) {
    		toDelete();
    	}
    }
    private class Retry implements OnClickListener {
    	@Override
    	public void onClick(DialogInterface dialog, int which) {
    		toQueryData();
    	}
    }
    private class Cancle implements OnClickListener {
		@Override
		public void onClick(DialogInterface dialog, int which) {
		}
    }
    
    private boolean isActive = true;
    @Override
    protected void onDestroy() {
    	isActive = false;
    	super.onDestroy();
    }
    
    private class PersonQueryAdapter extends BaseAdapter {

    	private ArrayList<Bundle> list;
    	private LayoutInflater inflater;
    	
    	public PersonQueryAdapter(ArrayList<Bundle> list, Context c) {
    		this.list = list;
    		inflater = LayoutInflater.from(c);
    	}
    	
		@Override
		public int getCount() {
			return list == null ? 0 : list.size();
		}

		@Override
		public Object getItem(int arg0) {
			return list.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

		@Override
		public View getView(int arg0, View convertView, ViewGroup arg2) {
			ViewHolder holder;
			if(convertView == null) {
				convertView = (LinearLayout)inflater.inflate(R.layout.tbperson_list_item, null);
				holder = new ViewHolder();
				holder.nameLyout = (LinearLayout)convertView.findViewById(R.id.lyout_name);
				holder.nameTxt = (TextView)convertView.findViewById(R.id.txt_name);
				holder.genderTxt = (TextView)convertView.findViewById(R.id.txt_gender);
				holder.nationTxt = (TextView)convertView.findViewById(R.id.txt_nation);
				holder.updateTxt = (TextView)convertView.findViewById(R.id.txt_update);
				holder.delTxt = (TextView)convertView.findViewById(R.id.txt_del);
				
				
				holder.nameLyout.getLayoutParams().width = nameWidth;
				holder.genderTxt.setWidth(genderWidth);
				holder.nationTxt.setWidth(nationWidth);
				holder.updateTxt.setWidth(updateWidth);
				holder.delTxt.setWidth(delWidth);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder)convertView.getTag();
			}
			
			Bundle bundle = list.get(arg0);
			holder.nameTxt.setText(bundle.getString("name"));
			holder.genderTxt.setText(bundle.getString("gender"));
			holder.nationTxt.setText(bundle.getString("nation"));
			holder.updateTxt.setTag(bundle.getString("guid"));
			holder.delTxt.setTag(bundle.getString("guid"));
			
			holder.updateTxt.setOnClickListener(new UpdateClickListener());
			holder.delTxt.setOnClickListener(new DelClickListener());
			
			return convertView;
		}
    }
    
    class ViewHolder {
    	LinearLayout nameLyout;
    	TextView nameTxt;
    	TextView genderTxt;
    	TextView nationTxt;
    	TextView updateTxt;
    	TextView delTxt;
    }
    
    private class DelClickListener implements android.view.View.OnClickListener {
    	@Override
    	public void onClick(View v) {
    		guid = (String)v.getTag();
    		toDelete();
    	}
    }
    
    private class UpdateClickListener implements android.view.View.OnClickListener {
		@Override
		public void onClick(View v) {
			guid = (String)v.getTag();
			Intent intent = new Intent(PListActivity.this, TBPersonEditActivity.class);
			intent.putExtra("guid", guid);
			intent.putStringArrayListExtra("nation", nationList);
			intent.putStringArrayListExtra("cardtype", cardtypeList);
			intent.putStringArrayListExtra("gender", genderList);
			PListActivity.this.startActivity(intent);
		}
    }
    
    private String guid;
    private void toDelete() {
    	proDialog = ProgressDialog.show(PListActivity.this, "请等待", "正在请求数据...",true,true);
    	new Thread() {
    		public void run() {
    			HashMap<String, String> params = new HashMap<String, String>();
    			params.put("guid", guid);
    			Bundle bundle = HttpUtils.getPost("delPerson.do", params, 3000, PListActivity.this);
    			
    			if(bundle.getInt("code") == HttpUtils.SUCCESS) {
    	    		String content = bundle.getString("content");
    	    		if(StringUtils.isBlank(content) || "{}".equals(content)) {
    	    			handler.sendEmptyMessage(HANDLER_DEL_CONN_ERROR);
    	    			return;
    	    		} else {
    	    			try {
    	    				JSONObject json = new JSONObject(content);
    	    				int success = json.getInt("success");
    	    				if(success == 1) {
    	    					handler.sendEmptyMessage(HANDLER_DEL_SUCCESS);
    	    				} else {
    	    					handler.sendEmptyMessage(HANDLER_DEL_ERROR);
    	    				}
    	    			} catch (Exception e) {
    	    				System.out.println(e);
    	    				handler.sendEmptyMessage(HANDLER_DEL_CONN_ERROR);
						}
    	    		}
    	    	} else {
    	    		handler.sendEmptyMessage(HANDLER_DEL_CONN_ERROR);
    	    	}
    		};
    	}.start();
    }
}
